package network.course5Http.https;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

public class HttpsClient {

    public  String readURLByHttpsGet(String url, String charset) throws Exception {
        //发送https前的准备工作
        TrustManager[] tm = {new TrainX509TrustManager()};
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        SSLSocketFactory ssf = sslContext.getSocketFactory();

        String content = "";
        try {
            // 创建URL对象
            URL net = new URL(url);
            InputStream in = null;
            HttpsURLConnection conn = (HttpsURLConnection) net.openConnection();//重要
            conn.setSSLSocketFactory(ssf);//重要
            conn.setConnectTimeout(60000);
            conn.setReadTimeout(60000);
            in = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, charset));
            StringBuffer sb = new StringBuffer();
            int ch;
            while ((ch = br.read()) != -1) {
                sb.append((char) ch);
            }
            in.close();
            content = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return content;
    }

    public static void main (String[] args)throws Exception {
        HttpsClient h=new HttpsClient();

        System.out.println(h.readURLByHttpsGet("https://www.17173.com","UTF-8"));
    }
}